// 如果以前引入过模块,那么他再次引入,其实是引入的缓存
//始终是1次,因为前面引入过了
import express from "express";
import DB from "./../../libs/DBHelper"
import multer from "multer";
import fs from "fs";

const multerObj = multer({
    dest: "./upload"
})
//1.创建保安 (高新聘请)
let apiRouter = express.Router();
//2.给保安大爷 安排 管理任务 

apiRouter.post("/login", (request, response, next) => {
    var prams = [request.body.uname, request.body.upwd];
    var loginSql = "SELECT uname,uid,utype FROM `usersinfo` WHERE uname=? AND upwd=?;";

    DB.exec(loginSql, prams, function (err, row) {
        if (err) {
            response.json({
                msg: err.message,
                status: -2
            })
        }
        if (row.length >= 1) {
            //登录成功,就把当前登录着的信息保存到session
            // session  能做什么? 用于在服务器端的 页面之间传值
            request.session["isLogin"] = row[0];
            response.json({
                msg: "登录成功",
                status: 1,
                data: row[0]
            })
        } else {
            response.json({
                msg: "登录失败",
                status: -1
            })
        }
    })

})


// vlidate remote:http://127.0.0.1:8080/api/checkuser
// 返回 true和fasle;

//检查用户名是否重复 已注释
apiRouter.get("/checkuser", async (request, response, next) => {
    let checkSql = "  SELECT uname FROM usersinfo WHERE uname=? ;";
    let params = request.query.uname;
    //await只能卸载 带有 async的函数内部  ES7  async/await
    // 解决异步
    var res = await DB.execAsync(checkSql, params);
    if (res.length >= 1) {
        response.end("true");
    } else {
        response.end("ok");
    }
})

// 3.注册逻辑
apiRouter.post("/reg", async function (request, response, next) {
    //1.准备sql语句
    let regSQL = "INSERT INTO usersinfo (`uname`,`upwd`)VALUES(?,?);";
    //2.准备参数
    var params = [request.body.uname, request.body.upwd];
    console.log(params)
    //3.执行sql语句.得到结果
    try {
        var res = await DB.execAsync(regSQL, params);
        if (res.affectedRows == 1) {
            response.json({
                msg: "恭喜您,注册成功!",
                status: 1 
            })
        } else {
            response.json({
                msg: "注册失败!",
                status: -1
            })
        }
    } catch (err) {
        response.json({
            msg: "注册异常",
            status: -3
        })
    }
})

//4.产品列表
apiRouter.get("/products", async (request, response, next) => {
    var productStr = fs.readFileSync("./data/list.json").toString();

    // response.json(对象)
    response.end(productStr);
})

//5.通过产品id,获得产品详细信息
apiRouter.get("/getproduct", async (request, response, next) => {
    // 获取数据的信息
    var productStr = fs.readFileSync("./data/list.json").toString();
   //将该信息转换成对象
    let productObj = JSON.parse(productStr);
    var resData = productObj.filter((el) => {
        console.log(el.p_id)
        return el.p_id == request.query.id
        
    })
    // response.json(对象)
    response.json(resData);
})

//加入购物车
apiRouter.post("/addCart",async(request, response, next)=>{

    let queryCart="SELECT*FROM `carts`  WHERE uid=? AND pid=?";

    let queryParams=[request.body.uid,request.body.pid];

    var res =await DB.execAsync(queryCart,queryParams);

    // 购买过
    if(res.length>=1){
        var updateCart=" UPDATE carts SET cnum=cnum + ?,ctotal=cprice*cnum WHERE uid=? AND pid=?;";
        let updatePramas=[
            request.body.cnum,
            request.body.uid,
            request.body.pid,
        ]

        let res = await DB.execAsync(updateCart, updatePramas);
        if (res.affectedRows == 1) {
            response.json({
                msg: "加入购物成功 u",
                status: 5
            })
        } else {
            response.json({
                msg: "加入购物失败 u",
                status: -5
            })
        }
    }else {
        //没购买

        let insertCart = "  INSERT  INTO `carts` (`pid`,`uid`,`cname`,`cnum`,`cprice`,`ctotal`,`cimg`,`poldprice`,`ptaxation`)VALUES(?,?,?,?,?,?,?,?,?);"

        let insertParams = [
            request.body.pid,
            request.body.uid,
            request.body.cname,
            request.body.cnum,
            request.body.cprice,
            request.body.ctotal,
            request.body.cimg,
            request.body.poldprice,
            request.body.ptaxation,
            

        ];
        

        var res = await DB.execAsync(insertCart, insertParams);
        if (res.affectedRows == 1) {
            response.json({
                msg: "加入购物成功 i", 
                status: 4
            })
        } else {
            response.json({
                msg: "加入购物失败 i",
                status: -4 
            })
        }
    }
})

//获取购物车列表

apiRouter.get("/getCart", async (request, response, next) => {

    let sql = " SELECT * FROM carts WHERE uid=?";
    //通过uid
    let prams = [request.query.uid];
    // 查询结果
    let res = await DB.execAsync(sql, prams);

    // 查询的结果
    var resObj = {
        status: 6,
        data: res,
        msg: "获取成功",
    }


    if (res.length == 0) {
        resObj["data"] = null;
        resObj["msg"] = "获取失败";
        resObj["status"] = "-6";
    }
    // 输出查询的结果
    response.json(resObj)
})

//修改
apiRouter.post("/modify", async (request, response, next) => {

    let sql = "UPDATE carts SET cnum=?,ctotal=cprice*cnum WHERE uid=? AND pid=?";

    let params = [
        request.body.cnum,
        request.body.uid,
        request.body.pid
    ]
    console.log(params)


    var res = await DB.execAsync(sql, params);
    if (res.affectedRows == 1) {
        
        response.json({
            msg: "修改购物成功",
            status: 7
        })
    } else {
        console.log(res.affectedRows)
        response.json({
            msg: "修改购物失败",
            status: -7
        })
    }

})

//删除
apiRouter.post("/delete", async (request, response, next) => {

    let sql = "  DELETE FROM `carts` WHERE cid=?;";
    let parms = [
        request.body.cid
    ]
    var res = await DB.execAsync(sql, parms);
    if (res.affectedRows == 1) {
        response.json({
            msg: "删除成功",
            status: 8
        })
    } else {
        response.json({
            msg: "删除失败",
            status: -8
        })
    }

})


    //实时查看购物的商量数量
    apiRouter.get("/getCunt", async (request, response, next) => {

        let sql = " SELECT SUM(cnum) AS totals FROM `carts` WHERE uid=? ;";

        let parmas = [
            request.query.uid
        ]

        var res = await DB.execAsync(sql, parmas);

        response.json({
            count: res[0].totals
        })
    })


//退出

apiRouter.get("/quit", async (request, response, next) => {

    //把session设置成空
    request.session = "";
    // 服务命令浏览器清除cookie
    response.clearCookie("tokenUser");

    // response.json({
    //     msg: "退出成功"
    // })
    // layer.msg("退出成功",{
    //     time:999,
    // })
    response.send("<script>alert('123')</script>")
})







apiRouter.post("/upload", multerObj.any(), (request, response, next) => {
    response.end("ok");
})


//暴露 保安大爷,去干活
module.exports = {
    apiRouter
}